package cn.cyj.security.security;

import cn.cyj.security.bean.DB_user;
import cn.cyj.security.dao.DB_user_dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DB_user_dao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        DB_user dbuser = userDao.findByUserName(username);

        if (dbuser == null) {
            throw new UsernameNotFoundException("不存在的用户名,请检查填写是否正确");
        }
        dbuser.setPassword(this.passwordEncoder.encode(dbuser.getPassword()));
        System.out.println("加密前-->" + dbuser.getPassword() + "  加密后-->" + dbuser.getPassword());
        return new User(username, dbuser.getPassword(), dbuser.isEnabled(), dbuser.isAccountNonExpired(), dbuser.isCredentialsNonExpired(), dbuser.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin,superUser,user,vipUser"));
    }
}
